import { Model, DataTypes, Optional } from 'sequelize';
import sequelize from '@/config/database';

// 字典数据属性接口
interface DictDataAttributes {
  dictCode: number;
  dictSort: number;
  dictLabel: string;
  dictValue: string;
  dictType: string;
  cssClass?: string;
  listClass?: string;
  isDefault?: string;
  status: string;
  createBy?: string;
  createTime?: Date;
  updateBy?: string;
  updateTime?: Date;
  remark?: string;
}

// 创建时可选字段
interface DictDataCreationAttributes extends Optional<DictDataAttributes, 'dictCode'> {}

// 字典数据模型
class DictData extends Model<DictDataAttributes, DictDataCreationAttributes> implements DictDataAttributes {
  public dictCode!: number;
  public dictSort!: number;
  public dictLabel!: string;
  public dictValue!: string;
  public dictType!: string;
  public cssClass?: string;
  public listClass?: string;
  public isDefault?: string;
  public status!: string;
  public createBy?: string;
  public createTime?: Date;
  public updateBy?: string;
  public updateTime?: Date;
  public remark?: string;

  // 时间戳
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;

  // 检查字典数据状态是否正常
  public isNormal(): boolean {
    return this.status === '0';
  }
}

DictData.init(
  {
    dictCode: {
      type: DataTypes.BIGINT,
      primaryKey: true,
      autoIncrement: true,
      field: 'dict_code',
      get() {
        const value = this.getDataValue("dictCode");
				return value !== undefined ? Number(value) : undefined;
      }
    },
    dictSort: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      field: 'dict_sort'
    },
    dictLabel: {
      type: DataTypes.STRING(100),
      allowNull: false,
      field: 'dict_label'
    },
    dictValue: {
      type: DataTypes.STRING(100),
      allowNull: false,
      field: 'dict_value'
    },
    dictType: {
      type: DataTypes.STRING(100),
      allowNull: false,
      field: 'dict_type'
    },
    cssClass: {
      type: DataTypes.STRING(100),
      field: 'css_class'
    },
    listClass: {
      type: DataTypes.STRING(100),
      field: 'list_class'
    },
    isDefault: {
      type: DataTypes.CHAR(1),
      defaultValue: 'N',
      field: 'is_default'
    },
    status: {
      type: DataTypes.CHAR(1),
      defaultValue: '0', // 0-正常，1-停用
      field: 'status'
    },
    createBy: {
      type: DataTypes.STRING(64),
      field: 'create_by'
    },
    createTime: {
      type: DataTypes.DATE,
      field: 'create_time'
    },
    updateBy: {
      type: DataTypes.STRING(64),
      field: 'update_by'
    },
    updateTime: {
      type: DataTypes.DATE,
      field: 'update_time'
    },
    remark: {
      type: DataTypes.STRING(500),
      field: 'remark'
    }
  },
  {
    sequelize,
    tableName: 'sys_dict_data',
    timestamps: true,
    createdAt: 'createTime',
    updatedAt: 'updateTime',
  }
);

export default DictData; 